<template>
  <div>
    <el-form
      :label-width="formConf.config.width+'px'"
      :label-position="formConf.config.position"
      :size="formConf.config.size"
      ref="dgFormMaking"
      :model="formValue">
      <el-row :gutter="50">
        <div
          :style="{display:formConf.config.inline?'inline':'block'}"
          v-for="widget in formConf.formData"
          :key="widget.id">
          <el-col v-show="widget.visible" :span="24" v-if="widget.type == 'p'">
            <p :style="{fontWeight:widget.fontWeight, fontSize:widget.fontSize+'px', color:widget.color, textAlign:widget.textAlign}">{{widget.content}}</p>
          </el-col>
          <el-col  v-show="widget.visible" :span="widget.span" v-else-if="widget.type == 'input'">
            <!-- input -->
            <el-form-item
              :label="widget.label"
              :prop="widget.name"
              :rules="[{required:widget.visible && !widget.disabled ? widget.required : false, message:'不可为空', trigger:bulrTrigger.indexOf(widget.type) > -1 ? 'blur' : 'change'},
                      {pattern: get_regex(widget.regex.rule), message: widget.regex.message}]">
              <el-input
                v-if="widget.type == 'input'"
                :placeholder="widget.placeholder"
                v-model="formValue[widget.name]"
                :disabled="widget.visible ? widget.disabled : true"
                @change="formChange($event, widget.name)">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col v-show="widget.visible" :span="widget.span" v-else>
            <el-form-item
              :label="widget.label"
              :prop="widget.name"
              :rules="{required:widget.visible && !widget.disabled ? widget.required : false, message:'不可为空', trigger:bulrTrigger.indexOf(widget.type) > -1 ? 'blur' : 'change'}">
              <!-- select -->
              <el-select
                v-if="widget.type == 'select'"
                v-model="formValue[widget.name]"
                :placeholder="widget.placeholder"
                style="width:100%;"
                :disabled="widget.visible ? widget.disabled : true"
                @change="formChange($event, widget.name)">
                <el-option
                  v-for="(option,index) in widget.options"
                  :key="index"
                  :label="option.label"
                  :value="option.value">
                </el-option>
              </el-select>
              <!-- radio -->
              <el-radio-group
                v-if="widget.type == 'radio'"
                v-model="formValue[widget.name]"
                :disabled="widget.visible ? widget.disabled : true"
                @change="formChange($event, widget.name)">
                <el-radio
                  v-for="(option,index) in widget.options"
                  :key="index"
                  :label="option.value">
                  {{option.label}}
                </el-radio>
              </el-radio-group>
              <!-- checkbox -->
              <el-checkbox-group
                v-if="widget.type == 'checkbox'"
                v-model="formValue[widget.name]"
                :disabled="widget.visible ? widget.disabled : true"
                @change="formChange($event, widget.name)">
                <el-checkbox
                  v-for="(option,index) in widget.options"
                  :key="index"
                  :label="option.value">
                  {{option.label}}
                </el-checkbox>
              </el-checkbox-group>
              <!-- date -->
              <el-date-picker
                v-if="widget.type == 'date'"
                v-model="formValue[widget.name]"
                :disabled="widget.visible ? widget.disabled : true"
                :placeholder="widget.placeholder"
                type="date"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                @change="formChange($event, widget.name)">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </div>
      </el-row>
      <el-form-item v-if="formConf.formData.length > 0 && showFooter">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="cancelSubmit">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
const axios = require('axios')
export default {
  name:'formRender',
  data(){
    return {
      formValue:{},
      bulrTrigger:['input','textarea'],
      formConf:{
        config:{
          width:70
        },
        formData:[]
      },
      showFooter:true
    }
  },
  props:['formRenderConf', 'formRenderValues', 'showButton'],
  watch:{
    formRenderConf:{
      handler:function(val){
        // 将props中的formBuilderConf赋值给formConf,以避免修改props值
        var obj_json = Object.assign({}, this.formConf, val)
        this.formConf = JSON.parse(JSON.stringify(obj_json))
        // 没有传入values的字段需要默认赋值
        var multiple_chioce = ['checkbox']
        var other_input = ['p']
        var conf = this.formConf.formData
        for (let index in conf) {
          var obj = conf[index]
          if (multiple_chioce.indexOf(obj.type) > -1){
            this.$set(this.formValue, obj['name'], [])
          } else if (other_input.indexOf(obj.type) === -1){
            this.$set(this.formValue, obj['name'], '')
          }
        }

        // 根据传入的value为表单赋值
        if (this.formRenderValues){
          var objCopy = {}
          for (let element in this.formRenderValues){
            objCopy[element] = this.formRenderValues[element]
          }
          this.formValue = Object.assign({}, this.formValue, objCopy)
        }
      },
      deep:true
    },
    formRenderValues:{
      handler:function(val){
        // 将props中的formBuilderConf赋值给formConf,以避免修改props值
        this.formConf = Object.assign({}, this.formConf, this.formRenderConf)

        // 没有传入values的字段需要默认赋值
        var multiple_chioce = ['checkbox']
        var other_input = ['p']
        var conf = this.formConf.formData
        for (let index in conf) {
          var obj = conf[index]
          if (multiple_chioce.indexOf(obj.type) > -1){
            this.$set(this.formValue, obj['name'], [])
          } else if (other_input.indexOf(obj.type) === -1){
            this.$set(this.formValue, obj['name'], '')
          }
        }

        // 根据传入的value为表单赋值
        var objCopy = {}
        for (let element in val){
          objCopy[element] = val[element]
        }
        this.formValue = Object.assign({}, this.formValue, objCopy)
      },
      deep:true
    },
    showButton:function(val){
      this.showFooter = val
    }
  },
  methods:{
    validate(){
      this.$refs['dgFormMaking'].validate((valid) => {
        if(valid){
          console.log("yes")
          return true
        } else {
          console.log("no")
          return false
        }
      })
    },
    formChange(value, name){
      var inputObj = {}
      inputObj[name] = value
      this.$emit('update:formRenderValues', JSON.parse(JSON.stringify(this.formValue)))
      this.$emit('dg-form-change', inputObj, JSON.parse(JSON.stringify(this.formValue)))
    },
    onSubmit(){
      this.$refs['dgFormMaking'].validate((valid) => {
        if (valid) {
          console.log("dgFormBuilder submit start!!!")
          this.$emit('submit', this.formValue)
        } else {
          console.log("dgFormBuilder is invalid , can not start submit!!!")
          return false;
        }
      })
    },
    cancelSubmit(){
      console.log("dgFormBuilder cancel submit!!!")
      this.$emit('cancel-submit')
    },
    get_regex(str){
      if(str) {
        return RegExp(str)
      } else {
        return null
      }
      
    },
    formRender() {
      // 将props中的formBuilderConf赋值给formConf,以避免修改props值
      var obj_json = Object.assign({}, this.formConf, this.formRenderConf)
      this.formConf = JSON.parse(JSON.stringify(obj_json))
      // 没有传入values的字段需要默认赋值
      var multiple_chioce = ['checkbox']
      var other_input = ['p']
      var conf = this.formConf.formData
      for (let index in conf) {
        var obj = conf[index]
        if (multiple_chioce.indexOf(obj.type) > -1) {
          this.$set(this.formValue, obj['name'], [])
        } else if (other_input.indexOf(obj.type) === -1) {
          this.$set(this.formValue, obj['name'], '')
        }
      }

      // 根据传入的value为表单赋值
      if (this.formRenderValues) {
        var objCopy = {}
        for (let element in this.formRenderValues) {
          objCopy[element] = this.formRenderValues[element]
        }
        this.formValue = Object.assign({}, this.formValue, objCopy)
      }

      // 是否显示底部提交和取消按钮
      if (typeof (this.showButton) === 'boolean') {
        this.showFooter = this.showButton
      }
    },
    async funA(){
      for (let i in this.formRenderConf.formData) {
      if (this.formRenderConf.formData[i].remote) {
        for (let k in this.formRenderConf.formData[i].headers) {
          axios.defaults.headers.common[this.formRenderConf.formData[i].headers[k].key] = this.formRenderConf.formData[i].headers[k].value
        }
        // 判断
        var wait = await axios.get(this.formRenderConf.formData[i].url)
          .then(res => {
            this.formRenderConf.formData[i].options = res.data
          })
          .catch(function (error) {
            console.log(error)
          })
       }
     }
     console.log(wait)
     this.formRender()
    }
  },
  beforeMount(){
      this.funA()
  },
  mounted(){
    // 如果有传入的values值，则覆盖formValues
    if (this.values){
      this.formValue = Object.assign({}, this.formvalue, this.values)
    }
  }
}
</script>
<style scoped>
</style>
